
window.$ = function(selector, context) {
  // an object containing the matching keys and native get commands
  var method = 'querySelectorAll';
  if(selector[0]=='#') {
      method = 'getElementById';
      selector = selector.slice(1);
  }
  var el = (((context === undefined) ? document: context)[method](selector));
  if(!el) return null;
  if(method == 'getElementById') return el;
  return ((el.length < 2) ? el[0]: el);
};

function extend() {
    var args = [].slice.call(arguments);
    for(var i=1,len=args.length; i < len; i++) {
        if(args[i]) {
            for(var key in args[i]) {
                var val = args[i][key];
                if(Object.prototype.toString.call(val) == "[object Object]") {
                    args[0][key] = extend({},val);
                } else {
                    args[0][key] = val;
                }
            }
        }
    }
    return args[0];
}

extend(window.Element.prototype,{
    '__uniqID': function(string) {
        string = string || '';
        return string + Math.random().toString(36).substr(2, 10);
    },
    '__evalDateset': function(old, nd) {
        if (old) {
            return old + '|' + nd;
        } else {
            return nd;
        }
    },
    '__camelize' : function(s) {
		return s.replace(/\-(.)/g, function(m, l){return l.toUpperCase()});
	},
    each: function(fn) {
        fn.call(this,this,0);
    },
    matches: Element.prototype.matchesSelector ||
                Element.prototype.mozMatchesSelector ||
                Element.prototype.msMatchesSelector ||
                Element.prototype.oMatchesSelector ||
                Element.prototype.webkitMatchesSelector ||
                function(s) {
                    var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                        i = matches.length;
                    while (--i >= 0 && matches.item(i) !== this) {}
                    return i > -1;
                },
    closestEl: function(selector, root) {
        var el = this;
        while (el) {
            parent = el.parentElement;
            if (parent && parent.matches(selector)) {
                return parent;
            }
            el = parent;
            if(root && el === root) { //只到最上级
                break;
            }
        }
        return null;
    },
    on: function(eventType, selector, callback) {
        eventType = eventType.split(' ');
        var eid = this.__uniqID(), self = this;

        for (var i = 0; i < eventType.length; i++) {
            if(typeof selector == 'function') {
                window[eid] = selector;
                this.dataset[eventType[i]] = this.__evalDateset(this.dataset[event], eid);
                this.addEventListener(eventType[i], window[eid]);
            } else {
                window[eid] = function(e) {
                    var els = this.querySelectorAll(selector),
                        target = e.target;
                    els.each(function(el,i) {
                        if(el == target) {
                            callback.call(target,e);
                            e.stopPropagation();
                            return false;
                        } else if(el.closestEl(selector,self)) {
                            callback.bind(target,e);
                            e.stopPropagation();
                            return false;
                        }
                    });
                };
                this.addEventListener(eventType[i], window[eid]);
                self.dataset[eventType[i]] = self.__evalDateset(self.dataset[event], eid);
            }
        }
        return this;
    },
    off: function(eventType, callback) {
        if(handle) {
            this.removeEventListener(eventType, callback);
        } else {
            if(callback = el.dataset[event]) {
                callback = handle.split('|');
                for(var i =0, len = handle.length; i < len; i ++) {
                    this.off(eventType, callback[i]);
                }
                this.dataset[eventType] = '';
            }
        }
    },
    addClass: function(cls) {
        if (!this.hasClass(cls)) this.className += " " + cls;
        return this;
    },
    removeClass: function(cls){
        if (this.hasClass(cls)) {
            this.className = this.className.replace(new RegExp('(\\s|^)' + cls + '(\\s|$)'), ' ');
        }
        return this;
    },
    hasClass: function(cls) {
        return this.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
    },
    css : function() {
        var self = this;
		if(typeof(arguments[0]) == "object"){
			var st = arguments[0];
			var elmStyle = this.style;
			for(var itm in st) {
				switch(itm) {
					case 'float':
						elmStyle['cssFloat'] = elmStyle['styleFloat'] = st[itm];
						break;
					case 'opacity':
						elmStyle.opacity = st[itm];
						elmStyle.filter = "alpha(opacity=" + Math.round(st[itm]*100) + ")";
						break;
					case 'className':
						this.className = st[itm];
						break;
					case 'width':
					case 'height':
						elmStyle[itm] = String(st[itm]).indexOf('%') > -1 ? st[itm] : parseInt(st[itm])+'px';
						break;
					default:
						if(arguments[1] !== true) {
                            var prefix = ['','-webkit-','-moz-','-o-'];
                            for(var i=0,len = prefix; i < len; i++) {
                                var it = self.__camelize(prefix[i]+itm);
                                if(typeof(elmStyle[it]) != 'undefined') {
									elmStyle[it] = st[itm];
                                    break;
								}
                            }
						} else {
							elmStyle[self.__camelize(itm)] = st[itm];
						}
				}
			}
			return this;
		}else if(typeof(arguments[0]) == "string"){
			var cssRule = arguments[0],d = arguments[1];
			var doc = document.defaultView;
			if(d){
				var obj = {};
				obj[cssRule] = d;
				this.css(obj);
				return this;
			}else if(this.nodeType == 1){
				var elmStyle = this.style;
				var oCssRule = cssRule;
                var prefix = ['','-webkit-','-moz-','-o-'];
                for(var i=0,len = prefix; i < len; i++) {
                    var it = prefix[i],
                        _it = self.__camelize(it+cssRule);
                    if(typeof(elmStyle[_it]) != 'undefined') {
                        cssRule = _it;
						oCssRule = it+oCssRule;
                        break;
                    }
                }
				return (doc && doc.getComputedStyle) ? doc.getComputedStyle( this, null ).getPropertyValue(oCssRule) : this.currentStyle[ cssRule ];
			}
		}
	},
    attr: function(at) {
		if(typeof(at)=='object'){
			for(var itm in at) {
				if(itm=='style'){
					this.style.cssText = at[itm];
				}else{
					this.setAttribute(itm,at[itm])
				}

			}
			return this;
		}else if(typeof(at)=='string'){
			if(arguments.length==2){
				this[at] = arguments[1];
			}else{
				if(at=='style'){
					return this.style.cssText;
				}else{
					return this.getAttribute(at);
				}
			}
			return this;
		}
	},
    html: function(html) {
        this.innerHTML = html;
    },
    hide: function() {
        this.css({'display':'none'},true);
    },
    show: function() {
        this.css({'display':'block'},true);
    }
});

extend(window.NodeList.prototype,{
    each: function(fn) {
        var nodes = [].slice.call(this);
        for(var i=0,len=nodes.length; i < len; i++) {
            if(fn.call(nodes[i],nodes[i],i,nodes) === false) break;
        }
    },
    on: function(eventType, selector, callback){
        this.each(function(el){
          el.on(eventType, selector, callback);
        });
        return this;
    },
    off: function(eventType, callback) {
        this.each(function(el){
          el.off(eventType, callback);
        });
        return this;
    },
    addClass: function(name){
        this.each(function(el) {
            el.classList.add(name);
        });
        return this;
    },
    removeClass: function(name){
        this.each(function(el) {
            el.classList.remove(name);
        });
        return this;
    },
    html: function(html) {
        this.each(function(el) {
            el.html(html);
        });
        return this;
    },
    hide: function() {
        this.each(function(el) {
            el.hide();
        });
    },
    show: function() {
        this.each(function(el) {
            el.show();
        });
    }
});

var utils = {
    checkValidate:function(val,reg) {
        var validateRegex = {
            'required' : /^.+$/,
            'phone' : /^1\d{10}$/,
            'smscode': /^\d{4}$/,
            'zipcode': /^\d{6}$/,
        }
        var regex = validateRegex[reg];
        if(!regex) {
            regex = new RegExp(reg);
        }
        return regex.test(val);
    },
    getFormParam: function (form) {
        var frm = typeof(form) == 'string' ? document.getElementById(form) : form;
        var params = [];
        for(var i=0,len = frm.elements.length; i < len; i++) {
            el = frm.elements[i];
            if(el.name && ((el.type !='radio'&&el.type != 'checkbox') || el.checked)) {
                if(el.dataset['validate']) {
                    if(!utils.checkValidate(el.value,el.dataset['validate'])) {
                        alertMsg(el.dataset['errmsg']);
                        return;
                    }
                }
                params.push(encodeURIComponent(el.name) +'='+ encodeURIComponent(el.value));
            }
        }
        return params;
    },
    getParam: function(name) {
    	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || '';
    },
    __request: {},
    ajax: function(config) {
        // console.log(config);

        var params = config.params || [],req;
    	if(Object.prototype.toString.call( params ) === '[object Object]') {
    		var p = [];
    		for(var k in params) {
    			p.push(encodeURIComponent(k)+'='+encodeURIComponent(params[k]));
    		}
    		params = p;
    	}
    	var url = config.url || '';



    	if(config.form) {
    		var frm = typeof(config.form) == 'string' ? document.getElementById(config.form) : config.form;
    		url = url || frm.action;
    		for(var i=0,len = frm.elements.length; i < len; i++) {
    			el = frm.elements[i];
    			if(el.name && ((el.type !='radio'&&el.type != 'checkbox') || el.checked)) {
    				if(el.dataset['validate']) {
    					if(!utils.checkValidate(el.value,el.dataset['validate'])) {
    						alertMsg(el.dataset['errmsg']);
    						return;
    					}
    				}
    				params.push(encodeURIComponent(el.name) +'='+ encodeURIComponent(el.value));
    			}
    		}
    	}

    	if(url.indexOf('?')>-1){ url += '&timestamp='+new Date().valueOf(); }else{ url += '?timestamp='+new Date().valueOf(); }


    	function sendRequest(url,postData,config) {
        if(utils.__request[url]) return;
        utils.__request[url] = true;
    		req = createXMLHTTPObject();
    		if (!req) return;
    		var method = (postData) ? "POST" : "GET";
    		req.open(method,url,true);
    		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    		if (postData)
    			req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    		req.onreadystatechange = function () {
    			if (req.readyState != 4) return;
    			if (req.status != 200 && req.status != 304) {
    				return;
    			}
          utils.__request[url] = true; = false;
    			(typeof(config.mask) != 'undefined') && config.mask.zmunmask && config.mask.zmunmask();
    			var res = eval('('+req.responseText+')');
    			if(config.callback) {
    				config.callback(res);
    			}
    			if(res.success) {
    				config.success && config.success(res);
    			} else {
    				(config.failure || function(res) {alertMsg(res.detail);})(res);
    			}
    		};
    		if (req.readyState == 4) return;
    		req.send(postData);
    	}

    	var XMLHttpFactories = [
    		function () {return new XMLHttpRequest()},
    		function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    		function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    		function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    	];

    	function createXMLHTTPObject() {
    		var xmlhttp = false;
    		for (var i=0;i<XMLHttpFactories.length;i++) {
    			try {
    				xmlhttp = XMLHttpFactories[i]();
    			}
    			catch (e) {
    				continue;
    			}
    			break;
    		}
    		return xmlhttp;
    	}
    	sendRequest(url,params.join('&'),config);
    	return req;
    }
}

var app = {
    init: function() {
        this.initCustomer();
        this.renderQuestions();
        this.bindEvent();
        $('#survey_form').on('click','i',function(e) {
            var index = parseInt(this.dataset['index']);
            $('i',this.parentNode).each(function(el,i){
                el.className = i <= Math.min(2,index) ? 'green' :
                    (i <= Math.min(6,index) ? 'yellow' : (i <= Math.min(9,index) ? 'red': 'gray'));
            })
            $('input',this.parentNode).value = index+1;
            $('em',this.parentNode.parentNode).html((index+1)+'分');
        });
    },
    initCustomer: function() {
        if(!window.openid) return;
        utils.ajax({
            url: '/api_hd_survey/initCustomer',
            params: {
                openid: openid,
                openid_md5: openid_md5,
                create_code: source,
                nickname:'',
                sex:'',
                province:'',
                city:'',
                country:'',
                headimgurl:''
            },
            success: function(res) {
                if(res.addon.join) {
                    $('.page-home p').show();
                } else {
                    $('.page-home strong').show();
                    $('.page-home strong').dataset['type'] = res.addon.bind ? 1 : 0;
                }
            }
        })
    },
    bindEvent: function() {
        $('.page-home strong').on('click',function(e) {
            var type = this.dataset['type'];
            $('.page-home').hide();
            if(type == 1) {
                $('.page-survey').show();
            } else {
                $('.page-login').show();
            }
        });
        $('.page-survey strong').on('click', function(e) {
            utils.ajax({
                url: '/api_hd_survey/submitSurvey',
                form: $('#survey_form'),
                success: function(res) {
                    alertMsg('提交成功！');
                    location.reload();
                }
            })
        });
        $('.page-login strong').on('click', function(e) {
            utils.ajax({
                url: '/api_hd_survey/bind',
                form: $('#form_bind'),
                success: function(res) {
                    $('.page-login').hide();
                    $('.page-survey').show();
                }
            })
        });
        $('#btnCode').on('click', function() {
            if($('#btnCode').dataset['disabled'] == 1) return;
            var phone = $('#customer_phone').value;
            if(!utils.checkValidate(phone,'phone')) {
                alertMsg('请填写正确的手机号!');
                $('#customer_phone').focus();
                return;
            }
            utils.ajax({
                url: '/api_hd_survey/getCode',
                params: {'customer_phone':phone},
                success: function(res) {
                    alertMsg('短信验证码已发送，请注意查收！');
                }
            });
            var timeId = 0,count = 60;
            $('#btnCode').html('60s');
            $('#btnCode').dataset['disabled'] = 1;
            (function fn(){
                count --;
                timeId = setTimeout(fn,1000);
                $('#btnCode').html(count+'s');
                if(count == 0) {
                    clearTimeout(timeId);
                    $('#btnCode').html('发送验证码');
                    $('#btnCode').dataset['disabled'] = 0;
                }
            })()

        });
    },
    renderQuestions: function() {
        var questions = [{
            "title": "服务启动",
            "content": [
                "保养/维修安排的便利性（通过电话，短信等，也包括和服务人员沟通的时间）",
                "灵活地安排您希望保养/维修的时间",
                "接车过程及时高效(您等待被招呼的时间，和服务顾问沟通的时间，钥匙交接和填写书面文件的时间)"
            ]
        },{
            "title": "服务顾问",
            "content": [
                "服务顾问礼貌",
                "服务顾问有求必应",
                "详细地解释保养/维修的内容和收费情况"
            ]
        },{
            "title": "经销商设施",
            "content": [
                "开车进/出经销商/服务站容易",
                "经销商/服务站所处位置便利",
                "经销商/服务站干净整洁",
                "顾客休息区舒适(包括座椅、娱乐设施、饮料点心)"
            ]
        },{
            "title": "服务后交车",
            "content": [
                "提车过程及时高效(等待被接待的时间，填写书面文件和提车)",
                "收费合理",
                "周到地协助我提车(如协助找到车辆、付款等)"
            ]
        },{
            "title": "服务质量",
            "content": [
                "完成整个保养/维修所花的时间",
                "保养/维修完成很彻底",
                "保养/维修后的车干净并且车况良好(无损坏，车内设置无变化)"
            ]
        }];
        var html = [];
        for(var i=0,len = questions.length; i<len; i++) {
            html.push('<dl>');
            html.push('<dt>'+questions[i].title+'</dt>');
            for(var j=0,jlen = questions[i].content.length;j<jlen;j++) {
                html.push('<dd><p>' + questions[i].content[j] +'</p><span>');
                var _h = [];
                for(var n=0;n<10;n++) {
                    _h.push('<i data-index="'+n+'" class="gray"></i>');
                }
                html.push(_h.join(''));
                html.push('<em></em><input type="hidden" data-validate="required" data-errmsg="请回答完整['+questions[i].title+']" name="question_'+(i+1)+'_'+(j+1)+'"/></span></dd>');
            }
            html.push('</dl>');
        }
        $('#survey_form').html(html.join(''));

    }
};
app.init();
